package com.jwds.digital.bios.business.service.service.belt.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwds.digital.bios.business.core.infrastructure.mapper.belt.BeltAnalyzeMapper;
import com.jwds.digital.bios.business.service.service.belt.IBeltPerformanceHourService;
import com.jwds.digital.bios.business.core.infrastructure.dto.belt.BeltPerformanceHourReqDTO;
import com.jwds.digital.bios.business.core.infrastructure.vo.belt.BeltPerformanceHourRespVO;
import com.jwds.digital.bios.business.core.infrastructure.dto.belt.assembler.BeltPerformanceHourAssembler;
import com.jwds.digital.bios.business.core.infrastructure.entity.belt.BeltPerformanceHour;
import com.jwds.digital.bios.business.core.infrastructure.mapper.belt.BeltPerformanceHourMapper;
import com.jwds.digital.bios.business.core.exceptions.RecordNotFoundException;
import com.jwds.tdc.framework.application.lib.page.PageRequest;
import com.jwds.tdc.framework.application.lib.page.PageResponse;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static java.time.temporal.ChronoUnit.MONTHS;

/**
 * 皮带效能小时表实现类
 *
 * @author 林柏云
 * @date 2024-10-24
 */
@Slf4j
@Service
public class BeltPerformanceHourServiceImpl extends ServiceImpl<BeltPerformanceHourMapper, BeltPerformanceHour> implements IBeltPerformanceHourService {

    @Autowired
    private BeltPerformanceHourMapper baseMapper;

    @Override
    public BeltPerformanceHourRespVO queryById(Long id) {
        if (id == null) {
            return null;
        }
        BeltPerformanceHour entity = baseMapper.selectById(id);
        return BeltPerformanceHourAssembler.entity2dto(entity);
    }

    @Override
    public PageResponse<BeltPerformanceHourRespVO> page(PageRequest<BeltPerformanceHourReqDTO> request) {
        BeltPerformanceHourReqDTO condition = request.getQueryCondition();
        Page<BeltPerformanceHourRespVO> page = new Page<>(request.getPageIndex(), request.getPageSize());
        IPage<BeltPerformanceHourRespVO> pageData = baseMapper.pageQuery(page, condition);
        return new PageResponse<>((Page<?>) pageData, pageData.getRecords());
    }

    @Override
    public List<BeltPerformanceHourRespVO> list(BeltPerformanceHourReqDTO reqDto) {
        return baseMapper.queryList(reqDto);
    }

    @Override
    public void add(BeltPerformanceHourReqDTO reqDto) {
        BeltPerformanceHour entity = BeltPerformanceHourAssembler.dto2entity(reqDto);
        baseMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchAdd(List<BeltPerformanceHourReqDTO> dtoList) {
        dtoList.forEach(this::add);
    }

    @Override
    public void update(BeltPerformanceHourReqDTO reqDto) {
        BeltPerformanceHour oldEntity = baseMapper.selectById(reqDto.getId());
        if (oldEntity == null) {
            throw new RecordNotFoundException();
        }
        BeltPerformanceHour newEntity = BeltPerformanceHourAssembler.dto2entity(reqDto, oldEntity);
        baseMapper.updateById(newEntity);
    }

    @Override
    public void delete(Long id) {
        BeltPerformanceHour oldEntity = baseMapper.selectById(id);
        if (oldEntity == null) {
            throw new RecordNotFoundException();
        }
        baseMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<Long> ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    @Override
    public BeltPerformanceHourRespVO analyze(BeltPerformanceHourReqDTO reqDto) {

        // 取开始和结束时间，保留小时及以上单位时间
        //    reqDto.setStartTime(reqDto.getStartTime().withMinute(0).withSecond(0).withNano(0));
        //    reqDto.setEndTime(reqDto.getEndTime().withMinute(0).withSecond(0).withNano(0));
        reqDto.setEndTime(LocalDateTime.now().withMinute(0).withSecond(0).withNano(0));
        reqDto.setStartTime(reqDto.getEndTime().minusHours(1));
        BeltPerformanceHourRespVO beltPerformanceHourRespVO = baseMapper.analyze(reqDto.getId(), reqDto.getStartTime().withMinute(0).withSecond(0).withNano(0), reqDto.getEndTime().withMinute(59).withSecond(59));
        List<LocalDateTime> timeList = getTimeList(reqDto.getStartTime().minusHours(7), reqDto.getEndTime(), ChronoUnit.HOURS);

        return getHourRespVO(reqDto, timeList, beltPerformanceHourRespVO, baseMapper, ChronoUnit.HOURS);
    }

    public static @NotNull BeltPerformanceHourRespVO getHourRespVO(BeltPerformanceHourReqDTO reqDto, List<LocalDateTime> timeList, BeltPerformanceHourRespVO beltPerformanceHourRespVO, BeltAnalyzeMapper mapper, ChronoUnit chronoUnit) {


        // 每个时间段的负载率和空载负载率
        List<BigDecimal> loadRateList = new ArrayList<>();
        List<BigDecimal> noLoadRateList = new ArrayList<>();
        // 负载分布级别 0-34 35-64 65-100 及其时间统计
        List<String> loadRateLevelList = Arrays.asList("0-34", "35-64", "65-100");
        List<BigDecimal> loadRateLevelListCount = new ArrayList<>();
        for (int i = 0; i < loadRateLevelList.size(); i++) {
            loadRateLevelListCount.add(BigDecimal.ZERO);
        }
        // 循环计算每个时间段的数据负载率和空载负载率
        for (int i = 0; i < timeList.size() - 1; i++) {
            LocalDateTime startTime = timeList.get(i);
            LocalDateTime endTime = timeList.get(i + 1);
            switch (chronoUnit) {
                case HOURS: {
                    startTime = startTime.withMinute(0).withSecond(0).withNano(0);
                    endTime = endTime.withMinute(59).withSecond(59);
                }
                break;
                case DAYS: {
                    startTime = startTime.withHour(0).withMinute(0).withSecond(0).withNano(0);
                    endTime = endTime.withHour(23).withMinute(59).withSecond(59);
                }
                break;
                case WEEKS: {
                    // 一周的开始时间
                    startTime = startTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).withHour(0).withMinute(0).withSecond(0).withNano(0);
                    endTime = endTime.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).withHour(23).withMinute(59).withSecond(59);
                }
                break;
                case MONTHS: {
                    startTime = startTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
                    endTime = endTime.with(TemporalAdjusters.lastDayOfMonth())
                            .withHour(23).withMinute(59).withSecond(59).withNano(0);
                }
                break;
            }
            BeltPerformanceHourRespVO temp = mapper.analyze(reqDto.getId(), startTime, endTime);
            if (temp == null) {
                loadRateList.add(BigDecimal.ZERO);
                noLoadRateList.add(BigDecimal.ZERO);
                continue;
            } else {
                loadRateList.add(temp.getAvgLoadRate());
                noLoadRateList.add(temp.getAvgNoLoadRate());
            }

            if (temp.getAvgLoadRate() != null) {
                // 负载分布级别 0-34 35-64 65-100 及其时间统计
                if (temp.getAvgLoadRate().compareTo(BigDecimal.valueOf(34)) <= 0) {
                    loadRateLevelListCount.set(0, loadRateLevelListCount.get(0).add(temp.getLoadRuntime()));
                } else if (temp.getAvgLoadRate().compareTo(BigDecimal.valueOf(34)) > 0 && temp.getAvgLoadRate().compareTo(BigDecimal.valueOf(64)) <= 0) {
                    loadRateLevelListCount.set(1, loadRateLevelListCount.get(1).add(temp.getLoadRuntime()));
                } else if (temp.getAvgLoadRate().compareTo(BigDecimal.valueOf(64)) > 0) {
                    loadRateLevelListCount.set(2, loadRateLevelListCount.get(2).add(temp.getLoadRuntime()));
                }
            }
        }
        if (beltPerformanceHourRespVO != null) {
            BigDecimal totalPowerConsumption = beltPerformanceHourRespVO.getTotalPowerConsumption();
            beltPerformanceHourRespVO.setLoadPowerConsumption(
                    beltPerformanceHourRespVO.getLoadPowerConsumption().divide(totalPowerConsumption, 2, RoundingMode.HALF_UP)
            );
            beltPerformanceHourRespVO.setNoLoadPowerConsumption(
                    beltPerformanceHourRespVO.getNoLoadPowerConsumption().divide(totalPowerConsumption, 2, RoundingMode.HALF_UP)
            );
            beltPerformanceHourRespVO.setSpikePowerConsumption(
                    beltPerformanceHourRespVO.getSpikePowerConsumption().divide(totalPowerConsumption, 2, RoundingMode.HALF_UP)
            );
            beltPerformanceHourRespVO.setPeakPowerConsumption(
                    beltPerformanceHourRespVO.getPeakPowerConsumption().divide(totalPowerConsumption, 2, RoundingMode.HALF_UP)
            );

        } else {
            beltPerformanceHourRespVO = new BeltPerformanceHourRespVO();
        }

        beltPerformanceHourRespVO.setTimeList(timeList);
        beltPerformanceHourRespVO.setLoadRateList(loadRateList);
        beltPerformanceHourRespVO.setNoLoadRateList(noLoadRateList);
        beltPerformanceHourRespVO.setLoadLevelList(loadRateLevelList);
        beltPerformanceHourRespVO.setLoadRateLevelListCount(loadRateLevelListCount);
        return beltPerformanceHourRespVO;
    }

    public static List<LocalDateTime> getTimeList(LocalDateTime start, LocalDateTime end, ChronoUnit timeUnit) {
        List<LocalDateTime> timeList = new ArrayList<>();
        LocalDateTime current = start;
        switch (timeUnit) {
            case HOURS:
                // 循环每小时添加
                while (!current.isAfter(end)) {
                    timeList.add(current);
                    current = current.plusHours(1); // 每次增加1小时
                }
                break;
            case DAYS:
                while (!current.isAfter(end)) {
                    timeList.add(current);
                    current = current.plusDays(1); // 每次增加1天
                }
                break;
            case WEEKS:
                while (!current.isAfter(end)) {
                    timeList.add(current);
                    current = current.plusWeeks(1); // 每次增加1周
                }
            case MONTHS:
                while (!current.isAfter(end)) {
                    timeList.add(current);
                    current = current.plusMonths(1); // 每次增加1月
                }
        }

        return timeList;
    }

}